<?php

namespace app\api\model;

class Labels extends Common
{
    static public function lists($users, $types = 1)
    {
        $user_labels = [];

        $labels = LabelsUser::where(['types' => $types, 'user_id' => ['in', $users]])->column('id, user_id, label_id');

        if ($labels) {
            $label_ids = array_column($labels, 'label_id');

            $label_contain = self::where(['id' => ['in', $label_ids]])->cache(86400)->column('id, name');

            foreach ($labels as $item) {
                if (isset($label_contain[$item['label_id']])) {
                    $user_labels[$item['user_id']][] = $label_contain[$item['label_id']];
                }
            }
        }

        return $user_labels;
    }

    static public function edit($labels, $user_id, $types = 1)
    {
        LabelsUser::destroy(['types' => $types, 'user_id' => $user_id]);

        $labels = explode(',', $labels);

        $contain = [];
        foreach ($labels as $item) {
            $contain[] = ['types' => $types, 'user_id' => $user_id, 'label_id' => $item];
        }

        if ($contain) {
            (new LabelsUser)->insertAll($contain);
        }
    }
}
